package cn.ctyun.ipush.web.controller;
import cn.ctyun.ipush.utils.MD5;
import cn.ctyun.ipush.web.user.bo.City;
import cn.ctyun.ipush.web.user.bo.MenuTreeNode;
import cn.ctyun.ipush.web.user.bo.MenuUserNode;
import cn.ctyun.ipush.web.user.bo.UserModel;
import cn.ctyun.ipush.web.user.constanst.SessionAttributeKeys;
import cn.ctyun.ipush.web.user.service.CityService;
import cn.ctyun.ipush.web.user.service.MenuService;
import cn.ctyun.ipush.web.user.service.UserAdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by yanghongbo on 2016/7/4.
 */
@Controller
@RequestMapping
public class UController {
    @Resource
    private UserAdminService userAdminService;
    @Resource
    private CityService cityService;
    @Resource
    private MenuService menuService;
    /**
     * 用于进入页面后，显示数据
     */
    @RequestMapping(value = "userIntoPage", method = RequestMethod.GET)
    public ModelAndView intoPage(HttpSession session,HttpServletRequest request){

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、判断登录与否
        //3、取出所有用户信息
        //4、
        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;

                //查询有无权限
                //查出所有User

                UserModel userModel = new UserModel();

                List userList = userAdminService.getUserAll(userModel);
                //显示这个人部门，所以用map<Key-User,Value-City>
                Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();

                for(Object o1:userList){
                    UserModel utmp = (UserModel)o1;
                    City city = new City();
                    if(utmp!=null){
                        if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                            city=cityService.findCityById(utmp.getCity());

                        }
                    }
                    map.put(utmp,city);
                }



                Map<String,Object> data = new LinkedHashMap<String,Object>();
                data.put("userMap",map);
                return new ModelAndView("userManager",data);
            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }

    }


    /**
     * 用于进入页面后，显示数据
     */
    @RequestMapping(value = "updatePasswordPage", method = RequestMethod.GET)
    public ModelAndView updatePasswordPage(HttpSession session,HttpServletRequest request){

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、判断登录与否
        //3、进入修改密码页面
        //4、
        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;

                //查询有无权限
                //查出所有User

                UserModel userModel = new UserModel();

                Map<String,Object> data = new LinkedHashMap<String,Object>();

                return new ModelAndView("updatePassword",data);
            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }

    }

    /**
     * 用于进入页面后，显示数据
     */
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public ModelAndView updatePassword(HttpSession session,HttpServletRequest request){

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、判断登录与否
        //3、进入修改密码页面
        //4、
        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;

                //查询有无权限
                //查出所有User

                UserModel userModel = new UserModel();
                userModel = systemUserModel;
                String oldPassword=request.getParameter("oldPassword");
                String newPassword=request.getParameter("newPassword");
                String reNewPassword=request.getParameter("reNewPassword");

                oldPassword=MD5.getMD5Code(oldPassword);
                newPassword=MD5.getMD5Code(newPassword);
                reNewPassword=MD5.getMD5Code(reNewPassword);

                if(oldPassword.equals(userModel.getUserPassword())){

                    if(newPassword!=null&&!"".equals(newPassword)){

                        if(newPassword.equals(reNewPassword)){

                            userModel.setUserPassword(newPassword);
                            if(userAdminService.updateUser(userModel)){
                                Map<String,Object> data = new LinkedHashMap<String,Object>();
                                data.put("msg","修改成功");
                                session.removeAttribute("userInfo");
                                request.getSession().setAttribute(SessionAttributeKeys.SESSION_ATTR_KEY_USERINFO, userModel);
                                return new ModelAndView("updatePassword",data);
                            }else {
                                Map<String,Object> data = new LinkedHashMap<String,Object>();
                                data.put("msg","修改失败");
                                return new ModelAndView("updatePassword",data);
                            }

                        }else{
                            Map<String,Object> data = new LinkedHashMap<String,Object>();
                            data.put("msg","新旧密码不一致");
                            return new ModelAndView("updatePassword",data);
                        }

                    }else{
                        Map<String,Object> data = new LinkedHashMap<String,Object>();
                        data.put("msg","新密码不能为空");
                        return new ModelAndView("updatePassword",data);
                    }

                }else {

                    Map<String,Object> data = new LinkedHashMap<String,Object>();
                    data.put("msg","旧密码有误");
                    return new ModelAndView("updatePassword",data);

                }



            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }

    }

    /**
     * 用于进入页面后，显示数据
     */
    @RequestMapping(value = "resetPassword", method = RequestMethod.GET)
    public ModelAndView resetPassword(HttpSession session,HttpServletRequest request){

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、判断登录与否
        //3、取出所有用户信息
        //4、
        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;

                //查询有无权限
                //查出所有User
                String userId=request.getParameter("userId");
                UserModel userModel = userAdminService.getUserById(userId);
                if(userModel !=null){
                    userModel.setUserPassword(MD5.getMD5Code("123456"));

                    if(userAdminService.updateUser(userModel)){
//显示这个人部门，所以用map<Key-User,Value-City>
                        Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();
                        UserModel userModel1 = new UserModel();
                        List userList = userAdminService.getUserAll(userModel1);
                        for(Object o1:userList){
                            UserModel utmp = (UserModel)o1;
                            City city = new City();
                            if(utmp!=null){
                                if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                                    city=cityService.findCityById(utmp.getCity());

                                }
                            }
                            map.put(utmp,city);
                        }



                        Map<String,Object> data = new LinkedHashMap<String,Object>();
                        data.put("userMap",map);
                        data.put("msg","初始化成功");
                        return new ModelAndView("userManager",data);
                    }else{
                        //显示这个人部门，所以用map<Key-User,Value-City>
                        Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();
                        UserModel userModel1 = new UserModel();
                        List userList = userAdminService.getUserAll(userModel1);
                        for(Object o1:userList){
                            UserModel utmp = (UserModel)o1;
                            City city = new City();
                            if(utmp!=null){
                                if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                                    city=cityService.findCityById(utmp.getCity());

                                }
                            }
                            map.put(utmp,city);
                        }



                        Map<String,Object> data = new LinkedHashMap<String,Object>();
                        data.put("userMap",map);
                        data.put("msg","初始化失败");
                        return new ModelAndView("userManager",data);
                    }

                }else {
                    //显示这个人部门，所以用map<Key-User,Value-City>
                    Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();
                    UserModel userModel1 = new UserModel();
                    List userList = userAdminService.getUserAll(userModel1);
                    for(Object o1:userList){
                        UserModel utmp = (UserModel)o1;
                        City city = new City();
                        if(utmp!=null){
                            if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                                city=cityService.findCityById(utmp.getCity());

                            }
                        }
                        map.put(utmp,city);
                    }



                    Map<String,Object> data = new LinkedHashMap<String,Object>();
                    data.put("userMap",map);
                    data.put("msg","初始化失败");
                    return new ModelAndView("userManager",data);
                }



            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }

    }

    /**
     * 用户检测配置的数据库信息是否可以链接
     */
    @RequestMapping(value = "addUserInfo", method = RequestMethod.POST)
    public ModelAndView addUserInfo(HttpServletRequest request){

        String userName=request.getParameter("userName");
        String password=request.getParameter("userPassword");
        String userRealName=request.getParameter("userRealName");
        String userPhone=request.getParameter("userPhone");
        String userCity=request.getParameter("userCity");
        String nick=request.getParameter("yixinNick");

        password= MD5.getMD5Code(password);

        String userId= UUID.randomUUID().toString();

        UserModel userModel = new UserModel();
        userModel.setUserModelId(userId);
        userModel.setCity(userCity);
        userModel.setUserLoginName(userName);
        userModel.setUserPassword(password);
        userModel.setUserPhone(userPhone);
        userModel.setUserRealname(userRealName);
        userModel.setNick(nick);


        if(userAdminService.saveUser(userModel)){
            UserModel userModel1 = new UserModel();
            List userList = userAdminService.getUserAll(userModel1);
            //显示这个人部门，所以用map<Key-User,Value-City>
            Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();

            for(Object o1:userList){
                UserModel utmp = (UserModel)o1;
                City city = new City();
                if(utmp!=null){
                    if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                        city=cityService.findCityById(utmp.getCity());

                    }
                }
                map.put(utmp,city);
            }



            Map<String,Object> data = new LinkedHashMap<String,Object>();
            data.put("userMap",map);
            data.put("msg","添加成功");
            return new ModelAndView("userManager",data);
        }else {
            Map<String,Object> data = new LinkedHashMap<String,Object>();
            data.put("msg","添加失败");
            return new ModelAndView("userManager",data);
        }

    }
    /**
     * 用户检测配置的数据库信息是否可以链接
     */
    @RequestMapping(value = "searchUser", method = RequestMethod.POST)
    public ModelAndView searchUser(HttpServletRequest request){

        String userName=request.getParameter("searchLoginName");
        String userRealName=request.getParameter("searchRealName");

        UserModel userModel = new UserModel();

        if(userName!=null&&!"".equals(userName)) {
            userModel.setUserLoginName(userName);
        }
        if(userRealName!=null&&!"".equals(userRealName)) {
            userModel.setUserRealname(userRealName);
        }




            List userList = userAdminService.getUserAll(userModel);
            //显示这个人部门，所以用map<Key-User,Value-City>
            Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();

            for(Object o1:userList){
                UserModel utmp = (UserModel)o1;
                City city = new City();
                if(utmp!=null){
                    if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                        city=cityService.findCityById(utmp.getCity());

                    }
                }
                map.put(utmp,city);
            }



            Map<String,Object> data = new LinkedHashMap<String,Object>();
            data.put("userMap",map);
            //data.put("msg","添加成功");
            return new ModelAndView("userManager",data);


    }

    @RequestMapping(value = "deleteUser", method = RequestMethod.POST)
    public ModelAndView deleteUser(HttpServletRequest request){

        String[] deUserList=request.getParameterValues("userList");


        for (int i=0;i<deUserList.length;i++){
            String userId = deUserList[i];

            userAdminService.deleteUser(userId);
        }



        UserModel userModel = new UserModel();
        List userList = userAdminService.getUserAll(userModel);
        //显示这个人部门，所以用map<Key-User,Value-City>
        Map<UserModel,City> map = new LinkedHashMap<UserModel,City>();

        for(Object o1:userList){
            UserModel utmp = (UserModel)o1;
            City city = new City();
            if(utmp!=null){
                if (!(utmp.getCity()==null&&"".equals(utmp.getCity()))){

                    city=cityService.findCityById(utmp.getCity());

                }
            }
            map.put(utmp,city);
        }



        Map<String,Object> data = new LinkedHashMap<String,Object>();
        data.put("userMap",map);
        //data.put("msg","添加成功");
        return new ModelAndView("userManager",data);


    }

    /**
     * 加载TABLE，显示数据并且4个一行显示
     */
    @RequestMapping(value = "iniTable", method = RequestMethod.GET)
    public ModelAndView iniRuleTable(HttpSession session,HttpServletRequest request){

        //算法详情
        //1、取出session 中的USER 查询dataSource 中的createUser
        //2、查询出来是一个LIST 粒度是表
        //3、根据数据库名、URL、数据库用户名 去重
        //4、多个表 合成一个LIST 返回
        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;///得到USER

                String databasename = request.getParameter("dataId");//得到这个database 名字

                // create user + dataname 确定一个 datasource
                //查出来这个datasource所有的tablename
                List<String> tableList = new ArrayList<String>();
                tableList.add("1");
                tableList.add("2");
                tableList.add("3");
                tableList.add("4");
                tableList.add("5");
                tableList.add("6");

                //组成一个二维数据
                List<List<String>> resultList = new ArrayList<List<String>>();
                List<String> siteList =null;
                for(int i=0;i<tableList.size();i++){

                    if(i%4==0){
                        if(i!=0){
                            resultList.add(siteList);
                        }
                        siteList = new ArrayList<String>();
                        siteList.add(tableList.get(i));
                    }
                    else{
                        siteList.add(tableList.get(i));
                    }
                }
                resultList.add(siteList);

                Map<String,Object> data = new LinkedHashMap<String,Object>();
                data.put("tableName",resultList);
                data.put("dataId",databasename);
                return new ModelAndView("ruleDataTable",data);
            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }

    }
    @RequestMapping(value = "addUserMenuList", method = RequestMethod.POST)
    public ModelAndView addUserMenuList(HttpSession session,HttpServletRequest request){

        UserModel systemUserModel = new UserModel();
        try {
            Object o=session.getAttribute("userInfo");
            if(o!=null){

                systemUserModel = (UserModel)o;///得到USER

        String userId = request.getParameter("userId");
        String[] menuList = request.getParameterValues("menuTreeNodeList");

        if (userId!=null&&!"".equals(userId)&&menuList!=null&&menuList.length!=0){

            //加载到权限配置页面
            //取得这个用户所有的菜单权限，放在一个List中
            //取出所有菜单
            //循环对比，已所有菜单为主，构建一个map
            if(menuService.deleteMenuByUser(userId)){

                for(int i=0;i<menuList.length;i++){

                    String menuId = menuList[i];

                    menuService.addMenuUser(menuId,userId);

                }

            }

            List<MenuUserNode> list = menuService.findByUser(userId);
            MenuTreeNode tree = new MenuTreeNode();
            List<MenuTreeNode> allList = menuService.findAllMenuTree(tree);//全部菜单
            Map<MenuTreeNode,Integer> map = new LinkedHashMap<MenuTreeNode, Integer>();
            if(list!=null&&!list.isEmpty()){

                //list 是权限菜单

                for (MenuTreeNode trmp:allList){

                    int index=0;
                    for(MenuUserNode urmp:list){
                        if(urmp.getMenuId().equals(trmp.getMenuTreeNodeId())){
                            index=1;
                        }
                    }
                    if(index==1){
                        map.put(trmp,1);
                    }else {
                        map.put(trmp,0);
                    }

                }



            }else{

                for (MenuTreeNode trmp:allList){

                        map.put(trmp,0);

                }


            }
            //Map 存着所有的Menu
            List<MenuTreeNode> levelOneList = new ArrayList<MenuTreeNode>();



            for (Map.Entry<MenuTreeNode,Integer> entry : map.entrySet()) {

                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if(entry.getKey().getMenuLevel()==1){
                    levelOneList.add(entry.getKey());
                }
            }


            //构建最终MAP
            Map<MenuTreeNode,Map<MenuTreeNode,Integer>> pushMap = new LinkedHashMap<MenuTreeNode, Map<MenuTreeNode, Integer>>();

            if(levelOneList!=null&&!levelOneList.isEmpty()){

                for(MenuTreeNode menuTreeNode:levelOneList){

                    Map<MenuTreeNode,Integer> tmMap= new LinkedHashMap<MenuTreeNode, Integer>();
                    for (Map.Entry<MenuTreeNode,Integer> entry : map.entrySet()) {

                        //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                        if(entry.getKey().getParentId()!=null) {
                            if (entry.getKey().getParentId().equals(menuTreeNode.getMenuTreeNodeId())) {
                                tmMap.put(entry.getKey(), entry.getValue());
                            }
                        }
                    }
                    pushMap.put(menuTreeNode,tmMap);
                }

            }


            Map<String,Object> data = new LinkedHashMap<String,Object>();
            data.put("menuMap",pushMap);
            data.put("userId",userId);
            data.put("msg","添加成功");


            //

            if (systemUserModel.getUserModelId().equals(userId)){
                //修改的是当前用户自己权限--更新下session

                session.removeAttribute("fristMenuMap");
                List<MenuUserNode> userlist = menuService.findByUser(systemUserModel.getUserModelId());

                if(userlist!=null&&!userlist.isEmpty()) {

                    MenuTreeNode menuLevelOne = new MenuTreeNode();
                    menuLevelOne.setMenuLevel(1);
                    List<MenuTreeNode> mOne = menuService.findAllMenuTree(menuLevelOne);

                    if (mOne != null && !mOne.isEmpty()) {

                        Map<MenuTreeNode, List<MenuTreeNode>> map1 = new LinkedHashMap<MenuTreeNode, List<MenuTreeNode>>();

                        for (MenuTreeNode treeNode : mOne) {
                            List sonlist = new ArrayList();

                            for (MenuUserNode userNode : userlist) {
                                MenuTreeNode m = menuService.findById(userNode.getMenuId());
                                if (m.getParentId().equals(treeNode.getMenuTreeNodeId())) {

                                    sonlist.add(m);

                                }

                            }
                            map1.put(treeNode, sonlist);


                        }

                        request.getSession().setAttribute("fristMenuMap", map1);
                    }
                }


            }

            //
            return new ModelAndView("userMenuManager",data);


        }else{

            return new ModelAndView("userManager",null);
        }
            }else{
                //没有登录。。。。跳回login
                return new ModelAndView("login",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login",null);
        }


    }

    @RequestMapping(value = "loadUserMenuList", method = RequestMethod.GET)
    public ModelAndView loadUserMenuList(HttpServletRequest request){

        String userId = request.getParameter("userId");

        if (userId!=null&&!"".equals(userId)){
            //加载到权限配置页面
            //取得这个用户所有的菜单权限，放在一个List中
            //取出所有菜单
            //循环对比，已所有菜单为主，构建一个map

            List<MenuUserNode> list = menuService.findByUser(userId);

            MenuTreeNode tree = new MenuTreeNode();
            List<MenuTreeNode> allList = menuService.findAllMenuTree(tree);//全部菜单
            Map<MenuTreeNode,Integer> map = new LinkedHashMap<MenuTreeNode, Integer>();
            if(list!=null&&!list.isEmpty()){

                //list 是权限菜单

                for (MenuTreeNode trmp:allList){

                    int index=0;
                    for(MenuUserNode urmp:list){
                        if(urmp.getMenuId().equals(trmp.getMenuTreeNodeId())){
                            index=1;
                        }
                    }
                    if(index==1){
                        map.put(trmp,1);
                    }else {
                        map.put(trmp,0);
                    }

                }



            }else{

                for (MenuTreeNode trmp:allList){

                    map.put(trmp,0);

                }


            }
            //Map 存着所有的Menu
            List<MenuTreeNode> levelOneList = new ArrayList<MenuTreeNode>();



            for (Map.Entry<MenuTreeNode,Integer> entry : map.entrySet()) {

                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if(entry.getKey().getMenuLevel()==1){
                    levelOneList.add(entry.getKey());
                }
            }


            //构建最终MAP
            Map<MenuTreeNode,Map<MenuTreeNode,Integer>> pushMap = new LinkedHashMap<MenuTreeNode, Map<MenuTreeNode, Integer>>();

            if(levelOneList!=null&&!levelOneList.isEmpty()){

                for(MenuTreeNode menuTreeNode:levelOneList){

                    Map<MenuTreeNode,Integer> tmMap= new LinkedHashMap<MenuTreeNode, Integer>();
                    for (Map.Entry<MenuTreeNode,Integer> entry : map.entrySet()) {

                        //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                        if(entry.getKey().getParentId()!=null) {
                            if (entry.getKey().getParentId().equals(menuTreeNode.getMenuTreeNodeId())) {
                                tmMap.put(entry.getKey(), entry.getValue());
                            }
                        }
                    }
                    pushMap.put(menuTreeNode,tmMap);
                }

            }


            Map<String,Object> data = new LinkedHashMap<String,Object>();
            data.put("menuMap",pushMap);
            data.put("userId",userId);

            return new ModelAndView("userMenuManager",data);


        }else{

            return new ModelAndView("userManager",null);
        }


    }
    @RequestMapping(value = "loadCity", method = RequestMethod.POST)
    @ResponseBody
    public List<List<String>> loadCity(HttpSession session, HttpServletRequest request) {
        UserModel systemUserModel = new UserModel();
        Object o = session.getAttribute("userInfo");
        if (o != null) {
            systemUserModel = (UserModel) o;
            City city = new City();
            List<City> cityList= cityService.findCityAll(city);


            List<List<String>> list = new ArrayList<List<String>>();
            if (cityList != null) {
                for (City cityTmp : cityList) {
                    List<String> tmpList = new ArrayList<String>();
                    tmpList.add(cityTmp.getCityId());
                    tmpList.add(cityTmp.getCityName());
                    list.add(tmpList);
                }
            }
            return list;
        } else {
            return null;
        }
    }


}